// share/sendOrcheckProject/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMoreHidden: 1,
    ExpireTime: '',
    cardId: 0,
    staffUid: 0,
    projectInfo: {},
    activetype: 1, //1充值，2核销
    cardtype: 1, //卡类型：1充值卡，2次卡，3时效卡
    money: '', //充值金额
    integral: 0, //积分
    integralJia: '',
    integralJian: '',
    integralOption: 1, //1减少,2增加（积分）
    payMoney: '', //应付金额
    showPopups: false,//弹窗
    realpay: 0,//弹窗的实付金额
    cardpay: 0//充值卡扣款
  },

  // 获取卡信息
  getCardUser: function (cid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardUser?cid=' + cid,
      success: function (res) {
        if (res.data.Code == 0) {
          let info = res.data.Data;
          let date = new Date();
          var date2 = new Date(Date.parse(info.ExpireTime.replace(/-/g, "/")));
          if (date2 < date) {
            info.isExpiretime = 1;
          } else {
            info.isExpiretime = 0;
          }
          let expireTime = info.ExpireTime.substr(0, 10);
          that.setData({
            projectInfo: info,
            ExpireTime: expireTime
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 开通或核销用户卡项目
  updateUserCard: function () {
    let that = this;
    let money = that.data.money;
    let integral = that.data.integral;
    let payMoney = that.data.payMoney;
    let projectInfo = that.data.projectInfo;
    let cardId = wx.getStorageSync("cardId");
    let urlparam = 'staffId=' + cardId + '&clientid=' + that.data.clientid + '&rand=' + Math.random();
    let checkbtn = that.data.checkbtn; //checkbtn=1客户详情页的核销按钮点进来的
    // 充值
    if (that.data.activetype == 1) {
      if (that.data.cardtype == 1 || that.data.cardtype == 2) {
        if (!payMoney) {
          that.checkWrite('请输入应付金额');
          return
        }
        if (!money) {
          that.checkWrite('请输入充值的金额或次数');
          return
        }
        if (money.substr(0, 1) == ".") {
          money = "0" + money;
        }
      } else {
        if (!payMoney) {
          payMoney = 0;
        }
        money = 0;
      }
      if (that.data.integralOption == 1) {
        if (!that.data.integralJian) {
          integral = 0;
        } else {
          integral = "-" + that.data.integralJian;
        }
      } else {
        if (!that.data.integralJia) {
          integral = 0;
        } else {
          integral = that.data.integralJia;
        }
      }
    }
    // 核销
    if (that.data.activetype == 2) {
      integral = 0;
      payMoney = 0;
      if (that.data.cardtype == 1 || that.data.cardtype == 2) {
        if (!money) {
          that.checkWrite('请输入消费金额或次数');
          return
        }
        if (money % 1 != 0) {
          var checkMoney = that.checkNumbers(money);
          if (!checkMoney) {
            that.checkWrite("请输入正确的金额");
            return;
          }
        }
      }
      money = "-" + money;
      if (money.substr(0, 1) == ".") {
        money = "-0" + money;
      }
      if (projectInfo.isExpiretime == 1) {
        wx.showToast({
          title: '该卡已过期',
          mask: true
        })
        return;
      }
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Coupon/UpdateCardUserBlance',
      data: {
        cid: that.data.cid,
        amount: parseFloat(money), //金额（次数）
        checkUid: app.globalData.userInfo.Uid,
        score: parseFloat(integral),
        payMoney: parseFloat(payMoney), //应付金额
        expireTime: that.data.ExpireTime,
        direction: that.data.activetype
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '已更新',
            duration: 2000,
            mask: true
          })
          if (checkbtn == 1) {
            setTimeout(function () {
              wx.navigateTo({
                url: '/pages/h5page/index?url=customerDetail.html&urlparam=' + encodeURIComponent(urlparam),
              })
            }, 2000);
          } else {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              })
            }, 2000);
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //消费卡核销
  updateUserCard2: function () {
    let that = this;
    let money = that.data.money;
    let projectInfo = that.data.projectInfo;
    let discount = projectInfo.Discount;
    if (that.data.cardtype == 1 || that.data.cardtype == 2) {
      if (!money) {
        that.checkWrite('请输入消费金额');
        return
      }
      if (money % 1 != 0) {
        var checkMoney = that.checkNumbers(money);
        if (!checkMoney) {
          that.checkWrite("请输入正确的金额");
          return;
        }
      }
    }
    let cardpay = parseFloat(money) * parseFloat(discount) / 100;
    if (cardpay > projectInfo.Balance) {
      cardpay = projectInfo.Balance;
    }
    cardpay = cardpay.toFixed(2);
    let realpay = parseFloat(money) - parseFloat(cardpay);
    realpay = realpay.toFixed(2);
    money = "-" + money;
    if (money.substr(0, 1) == ".") {
      money = "-0" + money;
    }
    if (projectInfo.isExpiretime == 1) {
      wx.showToast({
        title: '该卡已过期',
        mask: true
      })
      return;
    }
    that.setData({
      showPopups: true,
      realpay: realpay,
      cardpay: cardpay
    })
  },
  submitCardItem: function () {
    let that = this;
    that.closePopups();
    let money = "-" + that.data.cardpay;
    let integral = 0;
    let payMoney = that.data.realpay;
    let cardId = wx.getStorageSync("cardId");
    let urlparam = 'staffId=' + cardId + '&clientid=' + that.data.clientid + '&rand=' + Math.random();
    let checkbtn = that.data.checkbtn; //checkbtn=1客户详情页的核销按钮点进来的
    let projectInfo = that.data.projectInfo;
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Coupon/UpdateCardUserBlance',
      data: {
        cid: that.data.cid,
        amount: money, //金额（次数）
        checkUid: app.globalData.userInfo.Uid,
        score: parseFloat(integral),
        payMoney: parseFloat(payMoney), //应付金额
        expireTime: that.data.ExpireTime,
        direction: that.data.activetype
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          wx.showToast({
            title: '已更新',
            duration: 2000,
            mask: true
          })
          if (checkbtn == 1) {
            setTimeout(function () {
              wx.navigateTo({
                url: '/pages/h5page/index?url=customerDetail.html&urlparam=' + encodeURIComponent(urlparam),
              })
            }, 2000);
          } else {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              })
            }, 2000);
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 减积分
  jifenJianTap: function () {
    if (this.data.integral > 0) {
      var integral = this.data.integral;
      integral--;
      this.setData({
        integral: integral
      })
    }
  },

  // 加积分
  jifenJiaTap: function (e) {
    var integral = this.data.integral;
    integral++;
    this.setData({
      integral: integral
    })
  },
  // 加次数
  numJiaTap: function (e) {
    var money = this.data.money;
    money++;
    this.setData({
      money: money
    })
  },
  // 减次数
  numJianTap: function () {
    if (this.data.money > 1) {
      var money = this.data.money;
      money--;
      this.setData({
        money: money
      })
    }
  },

  // 充值
  toRecharge: function (e) {
    let activeType = e.currentTarget.dataset.activetype;
    let cardtype = e.currentTarget.dataset.cardtype;
    if (activeType == 1 && cardtype == 1) {
      wx.setNavigationBarTitle({
        title: '充值卡充值',
      })
    }
    if (activeType == 1 && cardtype == 2) {
      wx.setNavigationBarTitle({
        title: '次卡充值',
      })
    }
    this.setData({
      activetype: activeType,
      cardtype: cardtype,
      cid: this.data.projectInfo.Cid
    })
  },

  cancelActive: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let params = decodeURIComponent(options.scene);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let plist = '';
      if (params.indexOf('p-') != -1) {
        let param = params.match(/p-(\S*)/)[1];//参数
        plist = param.split('_');
      } else {
        let param = params.match(/p=(\S*)/)[1];//参数
        plist = param.split('#');
      }
      wx.setStorageSync('cardId', plist[3]);
      that.getCardUser(plist[0]);
      that.setData({
        activetype: plist[4],
        cardtype: plist[1],
        cid: plist[0],
        clientuid: plist[2]
      })
      if (plist[4] == 1) { //充值，
        if (plist[1] == 1) { //充值卡
          wx.setNavigationBarTitle({
            title: '充值卡充值',
          })
        }
        if (plist[1] == 2) { //次卡
          wx.setNavigationBarTitle({
            title: '次卡充值',
          })
        }
        if (plist[1] == 3) { //时效卡
          wx.setNavigationBarTitle({
            title: '年卡',
          })
        }
      }
      if (plist[4] == 2) { //核销，
        if (plist[1] == 1) { //充值卡
          wx.setNavigationBarTitle({
            title: '充值卡消费',
          })
        }
        if (plist[1] == 2) { //次卡
          wx.setNavigationBarTitle({
            title: '次卡消费',
          })
        }
        if (plist[1] == 3) { //时效卡
          wx.setNavigationBarTitle({
            title: '年卡消费',
          })
        }
      }
    } else {
      that.getCardUser(options.cid);
      that.setData({
        activetype: options.activetype,
        cardtype: options.cardtype,
        checkbtn: options.checkbtn,
        cid: options.cid,
        clientid: options.clientid,
        clientuid: options.clientuid
      })
      if (options.activetype == 1) { //充值，
        if (options.cardtype == 1) { //充值卡
          wx.setNavigationBarTitle({
            title: '充值卡充值',
          })
        }
        if (options.cardtype == 2) { //次卡
          wx.setNavigationBarTitle({
            title: '次卡充值',
          })
        }
        if (options.cardtype == 3) { //时效卡
          wx.setNavigationBarTitle({
            title: '年卡',
          })
        }
      }
      if (options.activetype == 2) { //核销，
        if (options.cardtype == 1) { //充值卡
          wx.setNavigationBarTitle({
            title: '充值卡消费',
          })
        }
        if (options.cardtype == 2) { //次卡
          wx.setNavigationBarTitle({
            title: '次卡消费',
          })
        }
        if (options.cardtype == 3) { //时效卡
          wx.setNavigationBarTitle({
            title: '年卡消费',
          })
        }
      }
    }
  },

  // 获取会员当前卡项目的消费记录
  getCardRecordList: function (staffUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardRecordList?uid=' + that.data.clientuid + '&cid=' + that.data.cid + '&createUid=' + staffUid + '&page=' + that.data.CurrentPage,
      success: function (res) {
        if (res.data.Code == 0) {
          let cardRecordsList = res.data.Data.List;
          if (that.data.CurrentPage != 1) {
            var preGoods = that.data.cardRecordsList
            cardRecordsList = preGoods.concat(cardRecordsList);
          }
          for (let i = 0; i < cardRecordsList.length; i++) {
            cardRecordsList[i].dTime = cardRecordsList[i].AddTime.substr(11, 8);
            cardRecordsList[i].AddTime = cardRecordsList[i].AddTime.substr(0, 10);
          }
          that.setData({
            cardRecordsList: cardRecordsList,
            loadingMoreHidden: res.data.Data.PageModel.TotalPages
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  cancelUpdate: function () {
    wx.navigateBack({
      delta: 1,
    })
  },

  // 获取名片信息
  getAiCardInfo: function () {
    var that = this;
    var cardId = wx.getStorageSync("cardId");
    if (!cardId) {
      cardId = that.data.cardId;
    }
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/GetAiCardDetail?uid=' + app.globalData.userInfo.Uid + '&staffId=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {
          let staffUid = res.data.Data.CardInfo.Uid;
          that.getCardRecordList(staffUid);
          that.data.staffUid = staffUid;
        } else {
          wx.showToast({
            title: '玖玖客加载失败',
            duration: 500
          })
          wx.redirectTo({
            url: '/pages/weijieke/cardList/index',
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (app.globalData.userInfo) {
      this.getAiCardInfo();
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },
  // 关闭弹窗
  closePopups: function () {
    this.setData({
      showPopups: false
    })
  },

  // 有效期
  bindDateChange: function (e) {
    this.setData({
      ExpireTime: e.detail.value
    })
  },
  // 积分
  bindIntegral: function (e) {
    this.setData({
      integral: e.detail.value
    })
  },
  //充值金额、次数
  bindMoney: function (e) {
    this.setData({
      money: e.detail.value
    })
  },
  // 应付金额
  bindPayMoney: function (e) {
    this.setData({
      payMoney: e.detail.value
    })
  },
  // 选择增加或减少积分
  selJiaOrJianIntegral: function (e) {
    let optionType = e.currentTarget.dataset.optiontype;
    this.setData({
      integralOption: optionType
    })
  },
  // 减积分
  bindIntegralJian: function (e) {
    this.setData({
      integralOption: e.currentTarget.dataset.optiontype,
      integralJian: e.detail.value,
      integralJia: ''
    })
  },
  // 加积分
  bindIntegralJia: function (e) {
    this.setData({
      integralOption: e.currentTarget.dataset.optiontype,
      integralJia: e.detail.value,
      integralJian: ''
    })
  },
  //填写判断
  checkWrite: function (str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  },
  // 加载更多
  loadMore: function (e) {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.CurrentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getCardRecordList(that.data.staffUid);
    } else {
      return
    }
  },
  // 小数点验证
  checkNumbers: function (value) {
    var returnVal = true;
    var inputZ = value;
    var ArrMen = inputZ.split("."); //截取字符串
    if (ArrMen.length > 2) {
      returnVal = false;
    }
    return returnVal;
  },
})